function RoomManager(connection, user, sound, dialog){
	var fn = this;		
	fn.user = user;	
	
	fn.init = function(){
		fn.createContent();
		fn.addEventListener();
	},
	
	fn.createContent = function(){
		fn.createHeaderBoard();
		fn.createRoomBoard();
		fn.createChatBoard();
	},
	
	fn.createHeaderBoard = function(){
		var container = $("<div></div>").addClass("ui-home-header-container");
		fn.backButton = $("<div></div>").addClass("ui-home-header-back");
		fn.headerTitle = $("<div></div>").addClass("ui-home-header-title");
		var userInfoGroup = $("<div></div>").addClass("ui-home-header-user-info-group");
		var vlAvatar = $("<div></div>").addClass("ui-home-header-user-avatar");
		var valueGroup = $("<div></div>").addClass("ui-home-header-user-group");
		var vlUsername = $("<div></div>").addClass("ui-home-header-user-value username");
		var vlBalance = $("<div></div>").addClass("ui-home-header-user-value balance");
		//fn.logoutButton = $("<div></div>").addClass("ui-home-header-logout");
		
		//user info group
		valueGroup.append(vlUsername);
		valueGroup.append(vlBalance);
		
		userInfoGroup.append(vlAvatar);
		userInfoGroup.append(valueGroup);
		
		//header group
		container.append(fn.backButton);
		container.append(fn.headerTitle);
		
		//container.append(fn.logoutButton);
		container.append(userInfoGroup);
		
		$(".ui-user-container").append(container);
		
		$(".ui-home-bottom-container").css("height", $(document).height() - 100);
		
		var widthW = $(document).width();
		if(widthW >= 768){ //full size
			$(".ui-room-container").css("width", widthW - 250);
			$(".ui-gameplay-home-container").css("width", widthW - 300);
		}
		
		//console.log($(document).height());
		
		$(window).resize(function(){
			$(".ui-home-bottom-container").css("height", $(document).height() - 100);
			
			var widthW = $(document).width();
			if(widthW >= 768){ //full size
				$(".ui-room-container").css("width", widthW - 250);
				$(".ui-gameplay-home-container").css("width", widthW - 300);
			}
		});
	},
	
	fn.createRoomBoard = function(){
		var searchGroup = $("<div></div>").addClass("ui-home-room-search-container");
		fn.tableGroup = $("<div></div>").addClass("ui-home-room-table-container");
		var createRoomGroup = $("<div></div>").addClass("ui-home-room-add-container");
		//create button
		fn.createRoomButton = $("<div></div>").addClass("ui-home-room-create-button");
		$(".ui-room-container").append(searchGroup);
		$(".ui-room-container").append(fn.createRoomButton);
		$(".ui-room-container").append(fn.tableGroup);
		$(".ui-room-container").append(createRoomGroup);
		
		fn.createSearchBoard();
		fn.createTableBoard();
		fn.createWindowAddRoom();
	},
	
	fn.createChatBoard = function(){
		//for room management
		var homeHeader = $("<div>" + I18n["public chat"] + "</div>").addClass("ui-home-chat-header");
		var chatHomeBody = $("<div></div>").addClass("ui-home-chat-body public");
		var homeGroup = $("<div></div>").addClass("ui-home-chat-group");
		fn.chatHomeInput = $("<input type='text'/>").addClass("ui-home-chat-input");
		
		homeGroup.append(fn.chatHomeInput);
		
		$(".ui-chat-container").append(homeHeader);
		$(".ui-chat-container").append(chatHomeBody);
		$(".ui-chat-container").append(homeGroup);
		
		chatHomeBody.niceScroll();
		
		//for game play
		var playheader = $("<div></div>").addClass("ui-home-chat-header");
		var chatPrivatePlayBody = $("<div></div>").addClass("ui-home-chat-body private");
		var chatPublicPlayBody = $("<div></div>").addClass("ui-home-chat-body public");
		var playGroup = $("<div></div>").addClass("ui-home-chat-group");
		fn.chatPlayInput = $("<input type='text'/>").addClass("ui-home-chat-input");
		
		var infoContainer = $("<div></div>").addClass("ui-home-chat-header-container");
		var tabContainer = $("<div></div>").addClass("ui-home-chat-header-container");
		
		var userInfoGroup = $("<div></div>").addClass("ui-home-header-user-info-group");
		var vlAvatar = $("<div></div>").addClass("ui-home-header-user-avatar");
		var valueGroup = $("<div></div>").addClass("ui-home-header-user-group");
		var vlUsername = $("<div></div>").addClass("ui-home-header-user-value username");
		var vlBalance = $("<div></div>").addClass("ui-home-header-user-value balance");
		fn.exitRoomButton = $("<div></div>").addClass("ui-home-header-logout");
		
		var privateTab = $("<div>" + I18n["private chat"] + "</div>").addClass("ui-home-chat-header-tab");
		var publicTab = $("<div>" + I18n["public chat"] + "</div>").addClass("ui-home-chat-header-tab");
		var indicatorTab = $("<div></div>").addClass("ui-home-chat-header-tab-indicator");
		
		//user info group
		valueGroup.append(vlUsername);
		valueGroup.append(vlBalance);
		
		userInfoGroup.append(vlAvatar);
		userInfoGroup.append(valueGroup);
		
		infoContainer.append(userInfoGroup);
		infoContainer.append(fn.exitRoomButton);
		
		tabContainer.append(privateTab);
		tabContainer.append(publicTab);
		tabContainer.append(indicatorTab);
		
		playheader.append(infoContainer);
		playheader.append(tabContainer);
		
		playheader.css("height", "120px");
		
		
		playGroup.append(fn.chatPlayInput);
		
		$(".ui-gameplay-chat-container").append(playheader);
		$(".ui-gameplay-chat-container").append(chatPrivatePlayBody);
		$(".ui-gameplay-chat-container").append(chatPublicPlayBody);
		$(".ui-gameplay-chat-container").append(playGroup);
		
		chatPrivatePlayBody.niceScroll();
		chatPublicPlayBody.niceScroll();
		
		privateTab.on("click touchend", function(){
			indicatorTab.css("margin-left", "0px");
			chatPrivatePlayBody.show();
			chatPublicPlayBody.hide();
			fn.isPublicChat = false;
		});
		
		publicTab.on("click touchend", function(){
			indicatorTab.css("margin-left", "50%");
			chatPrivatePlayBody.hide();
			chatPublicPlayBody.show();
			fn.isPublicChat = true;
		});
		
		fn.exitRoomButton.on("click touched", function(){

            var outFunction = function(){
                dataPlayers = [];
                $(".ui-gameplay-chat-container").removeClass("active");
                switchView(3);
                waitScene = new WaitScene();
                var director = cc.Director.getInstance();
                var currentScene = director.getRunningScene();
                if(currentScene.reset){
                    currentScene.reset();
                }
                else{
                    conn.sfs.send( new SFS2X.Requests.System.ExtensionRequest("callFinish", null, conn.sfs.lastJoinedRoom));
                }
                currentScene.removeAllChildren(true);
                director.replaceScene(waitScene);
            }

            if(isPlaying){
                dialog.showConfirmMessage(I18n["out room playing"], function(){
                    outFunction();
                }, function(){

                });
            }
            else{
                outFunction();
            }

		});
	},

	fn.createSearchBoard = function(){
		var form = $("<form method='get'/>");
		var leftBoard = $("<div></div>").addClass("ui-home-room-search-left");
		var rightBoard = $("<div></div>").addClass("ui-home-room-search-right");
		var groupButton = $("<div></div>").addClass("ui-home-room-search-button-group");
		form.append(leftBoard);
		form.append(rightBoard);
		form.append(groupButton);
		
		$(".ui-room-container .ui-home-room-search-container").append(form);
		
		//create left board
		//room owner
		var groupRoomOwner = $("<div></div>");
		var lbRoomOwner = $("<div>" + I18n["room owner"] + "</div>").addClass("ui-room-search-label");
		var txtRoomOwner = $("<input type='text'></input>").addClass("ui-room-search-input input-room-owner");
		groupRoomOwner.append(lbRoomOwner);
		groupRoomOwner.append(txtRoomOwner);
		
		//room name
		var groupRoomName = $("<div></div>");
		var lbRoomName = $("<div>" + I18n["room name"] + "</div>").addClass("ui-room-search-label");
		var txtRoomName = $("<input type='text'></input>").addClass("ui-room-search-input input-room-name");
		groupRoomName.append(lbRoomName);
		groupRoomName.append(txtRoomName);
		
		leftBoard.append(groupRoomOwner);
		leftBoard.append(groupRoomName);
		
		//create right board
		//start bet
		var groupStartBet = $("<div></div>");
		var lbStartBet = $("<div>" + I18n["room bet"] + "</div>").addClass("ui-room-search-label");
		var txtBeginStartBet = $("<input type='text' min='0'></input>").addClass("ui-room-search-input input-start-bet");
		var lbBetweenStartBet = $("<div>~</div>").addClass("ui-room-search-between-label");
		var txtEndStartBet = $("<input type='text' min='0'></input>").addClass("ui-room-search-input input-end-bet");
		groupStartBet.append(lbStartBet);
		groupStartBet.append(txtBeginStartBet);
		groupStartBet.append(lbBetweenStartBet);
		groupStartBet.append(txtEndStartBet);
		
		//room deposit
		/*var groupRoomDeposit = $("<div></div>");
		var lbRoomDeposit = $("<div>" + I18n["room deposit"] + "</div>").addClass("ui-room-search-label");
		var txtBeginRoomDeposit = $("<input type='text' min='0'></input>").addClass("ui-room-search-input input-start-room-deposit");
		var lbBetweenRoomDeposit = $("<div>~</div>").addClass("ui-room-search-between-label");
		var txtEndRoomDeposit = $("<input type='text' min='0'></input>").addClass("ui-room-search-input input-end-room-deposit");
		groupRoomDeposit.append(lbRoomDeposit);
		groupRoomDeposit.append(txtBeginRoomDeposit);
		groupRoomDeposit.append(lbBetweenRoomDeposit);
		groupRoomDeposit.append(txtEndRoomDeposit);*/
		
		rightBoard.append(groupStartBet);
		//rightBoard.append(groupRoomDeposit);
		
		//create button search and clear
		var div = $("<div></div>");
		fn.searchButton = $("<input type='submit' value=''/>").addClass("ui-home-search-button search-button");
		fn.clearButton = $("<div></div>").addClass("ui-home-search-button clear-button");
		
		div.append(fn.searchButton);
		div.append(fn.clearButton);
		
		groupButton.append(div);
		
		//init default value
		fn.vlRoomOwner = "";
		fn.vlRoomName = "";
		fn.vlStartBet = -1;
		fn.vlEndBet = -1;
		//fn.vlStartDeposit = -1;
		//fn.vlEndDeposit = -1;
	},
	
	fn.createTableBoard = function(){
		fn.tableGroup.niceScroll();
	},
	
	fn.createWindowAddRoom = function(){
		//header
		var groupHeader = $("<div></div>").addClass("ui-home-room-add-header");
		var title = $("<div>" + I18n["create new room"] + "</div>").addClass("ui-home-room-add-header-title");
		var closeHeaderButton = $("<div></div>").addClass("ui-home-room-add-header-close");
		groupHeader.append(title);
		groupHeader.append(closeHeaderButton);		
		
		//room name
		var groupRoomName = $("<div></div>").addClass("ui-home-room-add-room-content");
		var lbRoomName = $("<div>" + I18n["room name"] + "</div>").addClass("ui-room-add-label");
		var txtRoomName = $("<input type='text'></input>").addClass("ui-room-add-input input-room-name");
		groupRoomName.append(lbRoomName);
		groupRoomName.append(txtRoomName);
		
		//start bet
		var groupStartBet = $("<div></div>").addClass("ui-home-room-add-room-content");
		var lbStartBet = $("<div>" + I18n["room bet"] + "</div>").addClass("ui-room-add-label");
		var txtStartBet = $("<input type='text'></input>").addClass("ui-room-add-input input-room-bet");
		groupStartBet.append(lbStartBet);
		groupStartBet.append(txtStartBet);
		
		//room deposit
		/*var groupRoomDeposit = $("<div></div>").addClass("ui-home-room-add-room-content");
		var lbRoomDeposit = $("<div>" + I18n["room deposit"] + "</div>").addClass("ui-room-add-label");
		var txtRoomDeposit = $("<input type='text'></input>").addClass("ui-room-add-input input-room-deposit");
		groupRoomDeposit.append(lbRoomDeposit);
		groupRoomDeposit.append(txtRoomDeposit);*/
		
		//room password
		var groupRoomPassword = $("<div></div>").addClass("ui-home-room-add-room-content");
		var lbRoomPassword = $("<div>" + I18n["room password"] + "</div>").addClass("ui-room-add-label");
		var txtRoomPassword = $("<input type='password'></input>").addClass("ui-room-add-input input-room-password");
		groupRoomPassword.append(lbRoomPassword);
		groupRoomPassword.append(txtRoomPassword);
		
		//button create and close
		var buttonGroup = $("<div></div>").addClass("ui-home-room-add-room-content");
		var addButton = $("<div></div>").addClass("ui-home-room-add-button add-button");
		var closeButton = $("<div></div>").addClass("ui-home-room-add-button close-button");
		buttonGroup.append(addButton);
		buttonGroup.append(closeButton);
		
		//form container
		var form = $("<form />");
		form.append(groupHeader);
		form.append(groupRoomName);
		form.append(groupStartBet);
		//form.append(groupRoomDeposit);
		form.append(groupRoomPassword);
		form.append(buttonGroup);
		
		$(".ui-room-container .ui-home-room-add-container").append(form);
	},
	
	fn.addEventListener = function(){
		//return  choose mode
		fn.backButton.on("click touchend", function(){
			sound.clickEffect();
			switchView(2);
		});
		
		//logout
		/*fn.logoutButton.on("click touchend", function(){
			sound.clickEffect();
			connection.logout();
		});*/
		
		//search room
		fn.searchButton.on("click touchend", function(){
			sound.clickEffect();
			var container = $(".ui-home-room-search-container");
			
			fn.vlRoomOwner = container.find(".input-room-owner").val();
			fn.vlRoomName = container.find(".input-room-name").val();
			
			fn.vlStartBet = parseInt(container.find(".input-start-bet").val());
			if(isNaN(fn.vlStartBet) || fn.vlStartBet < 0){
				if(container.find(".input-start-bet").val() != ""){
					dialog.showErrorMessage(I18n["the starting bet is invalid"], function(){
						container.find(".input-start-bet").focus();
					});
					return false;
				}
				else{
					fn.vlStartBet = -1;
				}
			}
			
			fn.vlEndBet = parseInt(container.find(".input-end-bet").val());
			if(isNaN(fn.vlEndBet) || fn.vlEndBet < 0 || fn.vlEndBet < fn.vlStartBet){
				if(container.find(".input-end-bet").val() != ""){
					dialog.showErrorMessage(I18n["the ending bet is invalid"], function(){
						container.find(".input-end-bet").focus();
					});
					return false;
				}
				else{
					fn.vlEndBet = -1;
				}
				
			}
			
			/*fn.vlStartDeposit = parseInt(container.find(".input-start-room-deposit").val());
			if(isNaN(fn.vlStartDeposit) || fn.vlStartDeposit < 0){
				if(container.find(".input-start-room-deposit").val() != ""){
					dialog.showErrorMessage(I18n["the starting deposit is invalid"], function(){
						container.find(".input-start-room-deposit").focus();
					});
					return false;
				}
				else{
					fn.vlStartDeposit = -1;
				}
			}
			
			fn.vlEndDeposit = parseInt(container.find(".input-end-room-deposit").val());
			if(isNaN(fn.vlEndDeposit)|| fn.vlEndDeposit < 0 || fn.vlEndDeposit < fn.vlStartDeposit){
				if(container.find(".input-end-room-deposit").val() != ""){
					dialog.showErrorMessage(I18n["the ending deposit is invalid"], function(){
						container.find(".input-end-room-deposit").focus();
					});
					return false;
				}
				else{
					fn.vlEndDeposit = -1;
				}
			}*/
			
			fn.loadRoom();
			return false;
		});
		
		//clear search room
		fn.clearButton.on("click touchend", function(){
			sound.clickEffect();
			var container = $(".ui-room-container .ui-home-room-search-container");
			
			container.find(".input-room-owner").val("");
			container.find(".input-room-name").val("");
			container.find(".input-start-bet").val("");
			container.find(".input-end-bet").val("");
			container.find(".input-start-room-deposit").val("");
			container.find(".input-end-room-deposit").val("");
			fn.vlRoomOwner = "";
			fn.vlRoomName = "";
			fn.vlStartBet = -1;
			fn.vlEndBet = -1;
			//fn.vlStartDeposit = -1;
			//fn.vlEndDeposit = -1;
			
			fn.loadRoom();
		});
		
		var addRoomPopupContainer = $(".ui-room-container .ui-home-room-add-container");
		//show create add room popup
		fn.createRoomButton.on("click touchend", function(){
			sound.clickEffect();
			addRoomPopupContainer.show();
			var left = ($(window).width() - $(addRoomPopupContainer).width()) / 2;
			addRoomPopupContainer.css("left", left);
			addRoomPopupContainer.find("input[type='text']").val("");
			addRoomPopupContainer.find("input[type='password']").val("");
		});
		
		//clear add room popup
		addRoomPopupContainer.find(".close-button").on("click touchend", function(){
			addRoomPopupContainer.hide();
			sound.clickEffect();
		});
		
		addRoomPopupContainer.find(".ui-home-room-add-header-close").on("click touchend", function(){
			addRoomPopupContainer.hide();
			sound.clickEffect();
		});
		
		//add new room
		addRoomPopupContainer.find(".add-button").on("click touchend", function(){
			sound.clickEffect();
			var roomName = addRoomPopupContainer.find(".input-room-name").val();
			var roomBet = addRoomPopupContainer.find(".input-room-bet").val();
			//var roomDeposit = parseInt( addRoomPopupContainer.find(".input-room-deposit").val() );
			var roomPassword = addRoomPopupContainer.find(".input-room-password").val();
			
			if(roomName == ""){
				dialog.showErrorMessage(I18n["the room name is invalid"]);
				return;
			}
			if(isNaN(roomBet)){
				dialog.showErrorMessage(I18n["the room bet is invalid"]);
				return;
			}
			roomBet = parseInt(roomBet);
		    //pin

            var roomSettings  = {
                "roomName" : roomName,
                "roomBet" : roomBet,
                //"roomDeposit" : roomDeposit,
                "roomPassword": roomPassword,
                "playMode" : PLAY_MODE,
                "maxPlayer" : MAX_PLAYERS
            };

			

            var isSent = connection.createRoom(roomSettings);
            // Close panel
            if (isSent){
				dialog.showWaitingMessage(I18n["creating a room"]);
            }

            addRoomPopupContainer.hide();
		});
		
		
		//update rooms when having any changes on rooms
		connection.setRoomAddCallback(function(event){
            console.log("callback of setRoomAddCallback");
			dialog.hideMessage();
			addRoomPopupContainer.hide();
			var room = event.room;
			//user will join room if user create room
			var isJoined = room.isJoined;
			if(isJoined){
				//create new room and join it
				//fn.createRoom(room);
			}
			//update list rooms
			if (room.isGame  && !room.isHidden)
			{
				if (room.getVariable("playMode") != null)
				{
					if (room.getVariable("playMode").value != PLAY_MODE)
						return;
				}
				var roomID = room.id;
				var roomName = room.name;
				var roomOwner =  room.getVariable("roomOwner").value;
				var roomBet = room.getVariable("roomBet").value;
				//var roomDeposit = room.getVariable("roomDeposit").value;
				var maxPlayer = room.maxUsers;
				var currentPlayer = room.getUserCount();
				var roomState =  room.getVariable("roomState").value;
				var isLocked = room.isPasswordProtected;
				var users = room.getUserList();
				
				fn.addRoom(users, roomID, roomName, roomOwner, roomBet, maxPlayer, currentPlayer, roomState, isLocked);
			}
		});
		
		connection.setRoomAddErrorCallback(function(event){
			console.log(event);
			dialog.hideMessage();
			dialog.showErrorMessage(I18n[event.params.message], function(){
				dialog.hideMessage();
			});
		});
		
		connection.setRoomRemoveCallback(function(event){
			console.log(event);
			var roomID = event.room.id;
			fn.deleteRoom(roomID);
		});
		
		connection.setRoomJoinedCallback(function(event){
			if(event.room.name != LOBBY_ROOM_NAME){
			console.log(event);
            console.log("joined room");
			dialog.hideMessage();
			var room = event.room;
			var roomID = room.id;
			var roomName = room.name;
			var roomOwner =  room.getVariable("roomOwner").value;
			var roomBet = room.getVariable("roomBet").value;
			//var roomDeposit = room.getVariable("roomDeposit").value;
			var maxPlayer = room.maxUsers;
			var currentPlayer = room.getUserCount();
			var roomState =  room.getVariable("roomState").value;
			var isLocked = room.isPasswordProtected;
			var users = room.getUserList();

            CurrentRoomID = roomID;

			//fn.updateRoom(users, roomID, roomName, roomOwner, roomBet, maxPlayer, currentPlayer, roomState, isLocked);

			fn.createRoom(room);

				//store room ID
				fn.joinedRoomID = roomID;
				
				//clear chat
				$(".ui-home-chat-body.private").html("").show();
				$(".ui-home-chat-body.public").hide();
				fn.isPublicChat = false;

                switchView(4);
                cc.EGLView.getInstance()._resizeEvent();
                /*if(CurrentRoomID != -1 && CurrentRoomID == roomID) {
                    users = room.getUserList();
                    if(isDifferent(dataPlayers, users)){
                        dataPlayers = [];
                        for (var i = 0; i < users.length; i++) {
                            var obj = {};
                            obj.name = users[i].name;
                            obj.id = users[i].id;
                            if(users[i].getVariable("position")){
                                console.log("Join_" + obj.id + " " + (users[i].getVariable("position").value +1) );
                                obj.position = users[i].getVariable("position").value + 1;
                            }
                            else{
                                obj.position = i + 1;
                            }
                            obj.isCurrent = users[i].isItMe;
                            //obj.avatar = room.users[i].variables.avatar.value;
                            dataPlayers.push(obj);
                        }

                        if (waitScene != null) {
                            waitScene.addPlayers(dataPlayers);
                        }
                    }
                }*/

			}
		});
		
		connection.setRoomJoinErrorCallback(function(event){
			console.log(event);
			dialog.hideMessage();
			dialog.showErrorMessage(I18n[event.params.message], function(){
				dialog.hideMessage();
			});
		});
		
		connection.setUserEnterRoomCallback(function(event){
            if(event.room.name != LOBBY_ROOM_NAME) {
                console.log("User enter room");
                console.log(event);
                var room = event.room;
                var roomID = room.id;
                var roomName = room.name;
                var roomOwner = room.getVariable("roomOwner").value;
                var roomBet = room.getVariable("roomBet").value;
                //var roomDeposit = room.getVariable("roomDeposit").value;
                var maxPlayer = room.maxUsers;
                var currentPlayer = room.getUserCount();
                var roomState = room.getVariable("roomState").value;
                var isLocked = room.isPasswordProtected;
				var users = room.getUserList();

                fn.updateRoom(users, roomID, roomName, roomOwner, roomBet, maxPlayer, currentPlayer, roomState, isLocked);
                /*if(CurrentRoomID != -1 && CurrentRoomID == roomID) {
                    users = room.getUserList();
                    if(isDifferent(dataPlayers, users)){
                        dataPlayers = [];
                        for (var i = 0; i < users.length; i++) {
                            var obj = {};
                            obj.name = users[i].name;
                            obj.id = users[i].id;
                            if(users[i].getVariable("position")){
                                obj.position = users[i].getVariable("position").value + 1;
                                console.log("Enter_" + obj.id + " " + obj.position );
                            }
                            else{
                                obj.position = i + 1;
                            }

                            obj.isCurrent = users[i].isItMe;
                            //obj.avatar = room.users[i].variables.avatar.value;
                            dataPlayers.push(obj);
                        }

                        if (waitScene != null) {
                            waitScene.addPlayers(dataPlayers);
                        }
                    }
                }*/
            }

		});
		
		connection.setUserExitRoomCallback(function(event){
            if(event.room.name != LOBBY_ROOM_NAME) {
                console.log("User exit");
                console.log(event);
                var room = event.room;
                var roomID = room.id;
                var roomName = room.name;
                var roomOwner = room.getVariable("roomOwner").value;
                var roomBet = room.getVariable("roomBet").value;
                //var roomDeposit = room.getVariable("roomDeposit").value;
                var maxPlayer = room.maxUsers;
                var currentPlayer = room.getUserCount();
                var roomState = room.getVariable("roomState").value;
                var isLocked = room.isPasswordProtected;
				var users = room.getVariable("users").value;
				
				if(users.length > 1){

					fn.updateRoom(users, roomID, roomName, roomOwner, roomBet, maxPlayer, currentPlayer, roomState, isLocked);

                    /*if(CurrentRoomID != -1 && CurrentRoomID == roomID) {
                        users = room.getUserList();
                        if(isDifferent(dataPlayers, users)){
                            dataPlayers = [];
                            var isHaveOwner = false;
                            for (var i = 0; i < users.length; i++) {
                                var obj = {};
                                obj.name = users[i].name;
                                obj.id = users[i].id;
                                obj.position = users[i].getVariable("position").value + 1;
                                console.log("Exit_" + obj.id + " " + obj.position );
                                obj.isCurrent = users[i].isItMe;
                                dataPlayers.push(obj);
                                if (obj.id == RoomInfo.OwnerID) {
                                    isHaveOwner = true;
                                }
                            }

                            if (isHaveOwner) {
                                if (waitScene != null) {
                                    waitScene.addPlayers(dataPlayers);
                                }
                            }
                        }
                    }*/
				}
				else if(users.length == 1){
					//delete room
                    if(users[0].id != RoomInfo.OwnerID){
                        switchView(3);
                        fn.deleteRoom(roomID);
                    }
				}
            }

		});
		
		connection.setUserCountChangeCallback(function(event){
			if(event.room.name != LOBBY_ROOM_NAME){
                console.log("callback of setUserCountChangeCallback");
                console.log(event);
                var room = event.room;
                var roomID = room.id;
                var roomName = room.name;
                var roomOwner =  room.getVariable("roomOwner").value;
                var roomBet = room.getVariable("roomBet").value;
                //var roomDeposit = room.getVariable("roomDeposit").value;
                var maxPlayer = room.maxUsers;
                var currentPlayer = room.getUserCount();
                var roomState =  room.getVariable("roomState").value;
                var isLocked = room.isPasswordProtected;
				var users = room.getVariable("users").value;
				
				if(users.length > 0){

					/*fn.updateRoom(users, roomID, roomName, roomOwner, roomBet, maxPlayer, currentPlayer, roomState, isLocked);
                    if(CurrentRoomID != -1 && CurrentRoomID == roomID) {
                        dataPlayers = [];
                        users = room.getUserList();
                        for (var i = 0; i < users.length; i++) {
                            var obj = {};
                            obj.name = users[i].name;
                            obj.id = users[i].id;
                            obj.position = users[i].getVariable("position").value + 1;
                            console.log("Count_" + obj.id + " " + obj.position );
                            obj.isCurrent = users[i].isItMe;
                            //obj.avatar = room.users[i].variables.avatar.value;
                            dataPlayers.push(obj);
                        }

                        if (users[0] != undefined) {
                            RoomInfo.OwnerID = users[0].id;
                        }


                        if (waitScene != null) {
                            waitScene.addPlayers(dataPlayers);
                        }
                    }*/
				}
				else {
					//delete room
					fn.deleteRoom(roomID);
				}
			}
		});
		
		connection.setRoomUpdateCallback(function(event){
			console.log(event);
			var room = event.room;
			var roomID = room.id;
			var roomName = room.name;
			var roomOwner =  room.getVariable("roomOwner").value;
			var roomBet = room.getVariable("roomBet").value;
			//var roomDeposit = room.getVariable("roomDeposit").value;
			var maxPlayer = room.maxUsers;
			var currentPlayer = room.getUserCount();
			var roomState =  room.getVariable("roomState").value;
			var isLocked = room.isPasswordProtected;
			var users = room.getVariable("users").value;
			
			fn.updateRoom(users, roomID, roomName, roomOwner, roomBet, maxPlayer, currentPlayer, roomState, isLocked);
		});
		
		connection.setUserVarsUpdateCallback(function(event){
			//console.log(event);
			var user = event.user;
			var isMe = user.isItMe;
			
			if(isMe){
				fn.user.setUser(user);
				fn.updateUserInfo();
			}
		});
		
		fn.chatHomeInput.on("keydown", function(e){
			if (e.keyCode == 13) {
				var message = fn.chatHomeInput.val();
				if(message == ""){
					return;
				}
				
				var isSent = connection.sendPublicMessage(message);
			
				if (isSent){
					fn.chatHomeInput.val("");
				}
			}
		});
		
		fn.chatPlayInput.on("keydown", function(e){
			if (e.keyCode == 13) {
				var message = fn.chatPlayInput.val();
				if(message == ""){
					return;
				}
				
				var isSent = false;
				if(fn.isPublicChat){
					isSent = connection.sendPublicMessage(message);
				}
				else{
					isSent = connection.sendPrivateMessage(message, fn.joinedRoomID);
				}
			
				if (isSent){
					fn.chatPlayInput.val("");
				}
			}
		});
		
		//show new messages
		connection.setPublicMessageCallback(function(event){
			var sender = (event.sender.isItMe ? I18n["your remark"] : event.sender.getVariable("displayname").value + I18n["remark of"] );
			var message = $("<p><b>"+ sender +":</b>" + event.message + "</p>").addClass("ui-home-chat-content");
			
			if(event.room.name == LOBBY_ROOM_NAME){
			//detect is public message or private message
				$(".ui-home-chat-body.public").append(message);
			}
			else{
				$(".ui-home-chat-body.private").append(message);
			}
		});
		
		//show or hide chat board room management
		$(".ui-chat-button").on("click touched", function(){
			$(".ui-chat-container").toggleClass("active");
		});
		
		//show or hide chat board game play
		$(".ui-gameplay-chat-button").on("click touched", function(){
			$(".ui-gameplay-chat-container").toggleClass("active");
		});
	},
	
	fn.setFreeMode = function(){
		fn.headerTitle.html("<span>" + I18n["free mode"] + "</span>");
		PLAY_MODE = 0;
		fn.loadRoom();
		fn.updateUserInfo();
	},
	
	fn.setRealMode = function(){
		fn.headerTitle.html("<span>" + I18n["real mode"] + "</span>");
		PLAY_MODE = 1;
		fn.loadRoom();
		fn.updateUserInfo();
	},
	
	fn.updateUserInfo = function(){
		$(".ui-home-header-user-avatar").css("background-image","url('" + fn.user.getAvatar() + "')");
		$(".ui-home-header-user-value.username").html("<span>" + fn.user.getUsername() + "</span>");
		$(".ui-home-header-user-value.balance").html("<span>" + fn.user.getBalance() + " $</span>").css("font-size" , "25px");
	},
	
	//load all rooms from system
	fn.loadRoom = function(){	
		//clear old room
		fn.tableGroup.html("");
		var rooms = connection.getRoomLists();
		for(var i in rooms){
			var room = rooms[i];
			if (room.isGame  && !room.isHidden)
			{
				if (room.getVariable("playMode") != null)
				{
					if (room.getVariable("playMode").value != PLAY_MODE)
						continue;
				}
				var roomID = room.id;
				var roomName = room.name;
				var roomOwner =  room.getVariable("roomOwner").value;
				var roomBet = room.getVariable("roomBet").value;
				//var roomDeposit = room.getVariable("roomDeposit").value;
				var maxPlayer = room.maxUsers;
				var currentPlayer = room.getUserCount();
				var roomState =  room.getVariable("roomState").value;
				var isLocked = room.isPasswordProtected;
				var users = room.getVariable("users").value;
				
				fn.addRoom(users, roomID, roomName, roomOwner, roomBet, maxPlayer, currentPlayer, roomState, isLocked);
			}
		}
	},
	
	fn.addRoom = function(users, roomID, roomName, roomOwner, roomBet, maxPlayer, currentPlayer, roomState, isLocked){
		if(fn.vlRoomOwner != "" && roomOwner.toLowerCase().indexOf(fn.vlRoomOwner.toLowerCase()) == -1){
			return;
		}
		
		if(fn.vlRoomName != "" && roomName.toLowerCase().indexOf(fn.vlRoomName.toLowerCase()) == -1){
			return;
		}
		
		if(fn.vlStartBet != -1 && fn.vlEndBet != -1){
			if(roomBet < fn.vlStartBet || roomBet > fn.vlEndBet){
				return;
			}
		}
		else if(fn.vlStartBet != -1 && fn.vlEndBet == -1){
			if(roomBet < fn.vlStartBet){
				return;
			}
		}
		else if(fn.vlStartBet == -1 && fn.vlEndBet != -1){
			if(roomBet > fn.vlEndBet){
				return;
			}
		}
		
		var roomStatus = I18n["playing"];
		if (roomState == MatchState.WAIT_MORE_PLAYERS 
				|| roomState == MatchState.WAIT_PLAYERS_READY){
			roomStatus = I18n["waiting"];
		}
		
		var table = $("<div/>").addClass("ui-home-room-item");
		var slot1 = $("<div/>").addClass("ui-home-room-item-slot slot1");
		var slot2 = $("<div/>").addClass("ui-home-room-item-slot slot2");
		var slot3 = $("<div/>").addClass("ui-home-room-item-slot slot3");
		var slot4 = $("<div/>").addClass("ui-home-room-item-slot slot4");
		var roomPlay = $("<div/>").addClass("ui-home-room-item-play");
		var roomNameLb = $("<div/>").addClass("ui-home-room-item-name").html("<span>" + roomName + "</span>");
		//var roomOwner = $("<div/>").addClass("ui-home-room-item-owner").html("<span>" + roomOwner + "</span>");
		var roomBetLb = $("<div/>").addClass("ui-home-room-item-bet").html("<span>$ " + roomBet + "</span>");
		//var roomStatus = $("<div/>").addClass("ui-home-room-item-status").html("<span>" + roomStatus + "</span>");
		
		table.append(roomNameLb);
		//table.append(roomOwner);
		table.append(roomBetLb);
		//table.append(roomStatus);
		table.append(roomPlay);
		table.append(slot1);
		table.append(slot2);
		table.append(slot3);
		table.append(slot4);
		
		//set attributes
		table.attr("roomID", roomID);
		table.attr("roomName", roomName);
		table.attr("roomOwner", roomOwner);
		table.attr("roomBet", roomBet);
		table.attr("maxPlayer", maxPlayer);
		table.attr("currentPlayer", currentPlayer);
		table.attr("roomState", roomState);
		table.attr("isLocked", isLocked);
		
		fn.tableGroup.append(table);
		
		
		var slots = table.find(".ui-home-room-item-slot").css("background-image","url('')");
		for(var i = 0; i < users.length; i++){
			var user = users[i];
			var name = user.name;
			var avatar = user.avatar;
			$(slots[i]).css("background-image","url('" + avatar + "')");
		}
		
		table.on("click touchend", function(e){
			var id = parseInt($(this).attr("roomID"));
			var isLocked = $(this).attr("isLocked");
			var password = "";
			if(isLocked == "true"){
				dialog.showPromtMessage("Input password", function(val){
					password = val;
					var params =  {"roomID": id, "roomPassword": password};
					var isSent = fn.joinRoom(params);
					if(isSent){
						dialog.showWaitingMessage(I18n["joining a room"]);
					}	
				}, function(){
					return;
				});
			}
			else{
				var params =  {"roomID": id, "roomPassword": password};
				var isSent = fn.joinRoom(params);
				if(isSent){
					dialog.showWaitingMessage(I18n["joining a room"]);
				}	
			}
		});
	},
	
	fn.updateRoom = function(users, roomID, roomName, roomOwner, roomBet, maxPlayer, currentPlayer, roomState, isLocked){
        console.log("update room");
		var roomStatus = I18n["playing"];
		if (roomState == MatchState.WAIT_MORE_PLAYERS 
				|| roomState == MatchState.WAIT_PLAYERS_READY){
			roomStatus = I18n["waiting"];
		}
		
		var table = fn.tableGroup.find("div[roomID='" + roomID + "']");
		
		//set attributes
		table.attr("roomID", roomID);
		table.attr("roomName", roomName);
		table.attr("roomOwner", roomOwner);
		table.attr("roomBet", roomBet);
		table.attr("maxPlayer", maxPlayer);
		table.attr("currentPlayer", currentPlayer);
		table.attr("roomState", roomState);
		table.attr("isLocked", isLocked);
		
		//set values
		var childs = table.children();
		table.find(".ui-home-room-item-name").html("<span>" + roomName + "</span>");
		table.find(".ui-home-room-item-bet").html("<span>$ " + roomBet + "</span>");
		var slots = table.find(".ui-home-room-item-slot").css("background-image","url('')");
		for(var i = 0; i < users.length; i++){
			var user = users[i];
			var name = user.name;
			var avatar = user.avatar;
			$(slots[i]).css("background-image","url('" + avatar + "')");
		}
		
		
		/*$(tds[0]).html(roomName);
		$(tds[1]).html(roomOwner);
		$(tds[2]).html(roomBet);
		//$(tds[3]).html(roomDeposit);
		$(tds[4]).html(currentPlayer + "/" + maxPlayer);
		$(tds[5]).html(roomStatus);*/
	},
	
	fn.deleteRoom = function(roomID){
		var table = fn.tableGroup.find("div[roomID='" + roomID + "']");
		table.remove();
	},
	
	//create new room
	fn.createRoom = function(room){
		//console.log("create room");
        RoomInfo.roomID = room.id;

	},
	
	fn.joinRoom = function(params){
        console.log("join room and chagne view");

        connection.joinRoom(params);

		return true;
	}
};